<template>
  <nav-bar></nav-bar>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h2 style="user-select: none;">个人资料</h2>
          <el-button type="primary" @click="startEdit" v-if="!isEditing">编辑资料</el-button>
        </div>
      </template>

      <!-- 头像部分 -->
      <div class="avatar-section">
        <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-change="handleAvatarChange"
            :auto-upload="false"
        >
          <el-avatar
              :size="100"
              :src=photoUrl
              class="avatar"
          >
            A
          </el-avatar>
        </el-upload>
      </div>

      <!-- 个人信息表单 -->
      <el-form
          ref="profileForm"
          :model="formData"
          :rules="formRules"
          label-width="80px"
          v-loading="false"
      >


        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" disabled />
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" :disabled="!isEditing" />
        </el-form-item>
        <el-form-item label="分数" prop="score">
          <el-input v-model="formData.score" disabled />
        </el-form-item>

        <!-- 其他表单项... -->

        <!-- 编辑模式下显示按钮 -->
        <el-form-item v-if="isEditing">
          <el-button type="primary" @click="saveChanges">保存</el-button>
          <el-button @click="cancelEdit">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useStore } from 'vuex'; // 假设您在使用 Vuex
import { ElMessage } from 'element-plus';
import $ from 'jquery';
import NavBar from "@/components/NavBar.vue";

export default {
  components: {NavBar},
  setup() {
    const store = useStore(); // 获取 Vuex store
    const isEditing = ref(false);
    const formData = ref({
      score: '',
      email: '',
      username: '',
    });
    const photoUrl = ref('');

    const startEdit = () => {
      isEditing.value = true;
    };

    const cancelEdit = () => {
      isEditing.value = false;
      // Reset form data if needed
    };

    const saveChanges = () => {
      const { username } = formData.value;

      $.ajax({
        url: 'http://10.70.128.53:7090/api/user/updateUsername',
        type: 'POST',
        contentType: 'application/json',
        headers: {
          Authorization: `Bearer ${store.state.user.token}`,
        },
        data: JSON.stringify({
          userId: store.state.user.userId,
          username,
        }),
        success(resp) {
          if (resp.status === "success") {
            store.commit("updateUsername", username); // Update in store if needed
            isEditing.value = false;
            ElMessage.success(resp);
          } else {
            ElMessage.error(resp.message);
          }
        },
        error() {
          ElMessage.error("网络错误，请重试");
        },
      });
    };

    const beforeAvatarUpload = (file) => {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        ElMessage.error('上传头像图片只能是图片类型!');
      }
      return isImage;
    };

    const handleAvatarChange = (file) => {
      const formDataObj = new FormData();
      formDataObj.append('avatarFile', file.raw);

      $.ajax({
        url: 'http://10.70.128.53:7090/api/user/updateAvatar',
        type: 'POST',
        headers: {
          Authorization: `Bearer ${store.state.user.token}`,
          // 不要手动设置 Content-Type
        },
        data: formDataObj,
        processData: false, // 不处理数据
        contentType: false, // 不设置内容类型

        success(resp) {
          if (resp.status === "success") {

            const timestamp = new Date().getTime(); // 获取当前时间戳
            photoUrl.value = `${resp.data}?t=${timestamp}`; // 将时间戳作为查询参数添加到 URL,这个是要让watch函数启动
            console.log(resp);
            store.commit("updatePhoto", photoUrl.value); // 更新 store
            console.log(photoUrl.value)
            Refreshing()
            ElMessage.success(resp);
          } else {
            ElMessage.error(resp.message);
          }
        },

        error() {
          ElMessage.error("网络错误，请重试");
        }
      });
    };

    const Refreshing = () =>{
      const userInfo = store.state.user;
      formData.value.username = userInfo.username;
      formData.value.email = userInfo.email;
      photoUrl.value = userInfo.photo; // Assuming photo URL is stored in the state
      formData.value.score = userInfo.score;
      console.log(formData.value.score,userInfo.score,store.state.user.score);
      // console.log(formData.value.email);
    }
    onMounted(() => {
      Refreshing()

    });

    return {
      isEditing,
      formData,
      photoUrl,

      startEdit,
      cancelEdit,
      saveChanges,
      Refreshing,
      beforeAvatarUpload,
      handleAvatarChange,
    };
  },
};
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 800px;
  margin:10px auto;
  background-color: #f7f7f7;
}

.profile-card {
  background-color: var(--bg-color);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  color: var(--text-color-primary);
}

.avatar-section {
  text-align: center;
  margin-bottom: 30px;
}

.avatar-uploader {
  display: inline-block;
  position: relative;
  cursor: pointer;
}

.avatar {
  border: 2px solid var(--border-color);
  transition: all 0.3s;
}

.avatar-hover {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.5);
  border-radius:50%;
}

.avatar-uploader:hover .avatar-hover {
  opacity:.8;
}
</style>
